#include "area_manager.h"

namespace application {
namespace area {

AreaManager::AreaManager(int floor, std::shared_ptr<kernel::ILogger> logger, QObject* parent)
    : QObject(parent)
    , m_floor(floor)
    , m_logger(logger)
{
}

void AreaManager::addArea(std::shared_ptr<Area> area) {
    if (!area) {
        if (m_logger) {
            m_logger->warning("尝试添加空区域对象");
        }
        return;
    }

    QString areaId = area->getAreaId();
    m_areas.insert(areaId, area);

    connect(area.get(), &Area::areaEntered, this,
            [this](int agvId, const QString& areaId) {
                emit areaEntered(areaId, agvId);
                emit areaOccupationChanged(areaId);
            });
    connect(area.get(), &Area::areaExited, this,
            [this](int agvId, const QString& areaId) {
                emit areaExited(areaId, agvId);
                emit areaOccupationChanged(areaId);
            });
    connect(area.get(), &Area::occupationChanged, this,
            [this, areaId](bool) {
                emit areaOccupationChanged(areaId);
            });

    if (m_logger) {
        m_logger->debug(QString("区域已添加: %1 (楼层: %2)").arg(areaId).arg(m_floor));
    }

    emit areaAdded(areaId);
}

void AreaManager::removeArea(const QString& areaId) {
    if (m_areas.remove(areaId) > 0) {
        if (m_logger) {
            m_logger->debug(QString("区域已移除: %1").arg(areaId));
        }
        emit areaRemoved(areaId);
    }
}

std::shared_ptr<Area> AreaManager::getArea(const QString& areaId) const {
    return m_areas.value(areaId, nullptr);
}

bool AreaManager::hasArea(const QString& areaId) const {
    return m_areas.contains(areaId);
}

QList<QString> AreaManager::getAllAreaIds() const {
    return m_areas.keys();
}

std::shared_ptr<Area> AreaManager::findAreaContainingPoint(const kernel::Position& position) const
{
    for (auto it = m_areas.constBegin(); it != m_areas.constEnd(); ++it) {
        const auto& area = it.value();
        if (area && area->containsPoint(position)) {
            return area;
        }
    }
    return nullptr;
}

void AreaManager::enterArea(const QString& areaId, int agvId) {
    auto area = getArea(areaId);
    if (area) {
        area->enterArea(agvId);
    } else if (m_logger) {
        m_logger->warning(QString("区域不存在: %1").arg(areaId));
    }
}

void AreaManager::exitArea(const QString& areaId, int agvId) {
    auto area = getArea(areaId);
    if (area) {
        area->exitArea(agvId);
    } else if (m_logger) {
        m_logger->warning(QString("区域不存在: %1").arg(areaId));
    }
}

void AreaManager::initializeAreas() {
    if (m_logger) {
        m_logger->info(QString("初始化楼层 %1 的区域管理器").arg(m_floor));
    }
    // 这里可以从配置或地图数据加载区域信息
}

} // namespace area
} // namespace application
